package com.moyu.user.controller;

import com.moyu.common.core.contants.HttpConstants;
import com.moyu.common.core.controller.BaseController;
import com.moyu.common.core.domain.R;
import com.moyu.common.core.domain.TableDataInfo;
import com.moyu.user.domain.user.dto.UserRoleQueryDTO;
import com.moyu.user.domain.user.dto.*;
import com.moyu.user.domain.user.vo.DataTotalVO;
import com.moyu.user.domain.user.vo.LoginUserVO;
import com.moyu.user.domain.user.vo.UserHotVO;
import com.moyu.user.domain.user.vo.UserPostListVO;
import com.moyu.user.service.IStatsService;
import com.moyu.user.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户控制器
 *
 * @Author 赵彦博
 * @Date 2025/3/25 18:28
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户接口")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IStatsService statsService;


    // 增删查改
    // 邮箱注册账号
    @Operation(summary = "新增用户", description = "根据提供的信息新增用户")
    @PostMapping("/register")
    public R register(HttpServletRequest request, @RequestBody UserSaveDTO userSaveDTO) {
        return userService.register(request, userSaveDTO);
    }


    @Operation(summary = "发送邮箱验证码", description = "发送邮箱验证码")
    @GetMapping("/sendEmailCode")
    public R sendEmailCode(HttpServletRequest request, @RequestParam(value = "emailAddress", required = true) String emailAddress) {
        return userService.sendEmailCode(request, emailAddress);
    }

    @PostMapping("/login")  //安全
    @Operation(summary = "用户登录", description = "根据账号密码进行用户登录")
    @ApiResponse(responseCode = "1000", description = "操作成功")
    @ApiResponse(responseCode = "2000", description = "服务繁忙请稍后重试")
    @ApiResponse(responseCode = "3102", description = "用户不存在")
    @ApiResponse(responseCode = "3103", description = "用户名或密码错误")
    public R<String> login(@RequestBody LoginDTO loginDTO) {
        return userService.login(loginDTO.getUserAccount(), loginDTO.getPassword());
    }

    @Operation(summary = "用户退出", description = "当前用户登出")
    @DeleteMapping("/logout")
    public R<Void> logout(@RequestHeader(HttpConstants.AUTHENTICATION) String token) {
        return toR(userService.logout(token));
    }

    @GetMapping("/info")
    public R<LoginUserVO> info(@RequestHeader(HttpConstants.AUTHENTICATION) String token) {
        return userService.info(token);
    }

    @GetMapping("/list")
    public TableDataInfo list(UserQueryDTO userQueryDTO) {
        return getTableDataInfo(userService.list(userQueryDTO));
    }

    @PutMapping("/updateStatus")
    //todo 拉黑：限制用户操作   解禁：放开对于用户限制
    //更新数据库中用户的状态信息。
    public R<Void> updateStatus(@RequestBody UserDTO userDTO) {
        return toR(userService.updateStatus(userDTO));
    }

    @GetMapping("/role")
    public TableDataInfo getRole(UserQueryDTO userQueryDTO) {
        return getTableDataInfo(userService.getRole(userQueryDTO));
    }

    @GetMapping("/availableRoles")
    public TableDataInfo getAvailableRoles(UserRoleQueryDTO queryDTO) {
        return getTableDataInfo(userService.getAvailableRoles(queryDTO));
    }

    @PostMapping("/role/add")
    public R addUserRole(@RequestBody UserRoleDTO dto) {
        return toR(userService.addUserRole(dto));
    }

    @DeleteMapping("/role/remove")
    public R removeUserRole(@RequestBody UserRoleDTO dto) {
        return toR(userService.removeUserRole(dto));
    }

    @GetMapping("/online-count")
    public R<Long> getOnlineCount() {
        return R.ok(statsService.getOnlineCount());
    }

    @GetMapping("/total-visits")
    public R<Long> getTotalVisits() {
        return R.ok(statsService.getTotalVisits());
    }

    @GetMapping("/recent-logins")
    public List<Map<String, Object>> getRecentLogins() {
        return statsService.getRecentLogins();
    }

    @GetMapping("/getHotUser")
    public List<UserHotVO> getHotUser() {
        return userService.getHotUser();
    }

    @GetMapping("/getTotal")
    public DataTotalVO getTotal() {
        return userService.getTotal();
    }

    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestHeader(HttpConstants.AUTHENTICATION) String token,@RequestBody UserUpdateDTO dto) {
        return  toR(userService.updateUserInfo(token,dto));
    }

    @PostMapping("/changePassword")
    public R changePassword(@RequestBody UserUpdatePasswordDTO dto) {
        return toR(userService.changePassword(dto));
    }

    @GetMapping("/getUserPosts")
    public List<UserPostListVO> getUserPosts(String userId) {
        return userService.getUserPosts(userId);
    }

    @PostMapping("/updateAvatar")
    public R updateAvatar(MultipartFile file,String userId) {
        // 处理文件保存逻辑
        String fileName = saveFile(file);
        // 更新用户头像信息到数据库
        return toR(userService.updateAvatar(fileName,userId));
    }

    @Value("${file.upload.path}")
    private String uploadPath;

    private String saveFile(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            String filePath = uploadPath + fileName;
            file.transferTo(new java.io.File(filePath));
            return "/src/assets/images/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("文件保存失败", e);
        }
    }

    @GetMapping("/getUserInfoOther")
    public R<LoginUserVO> getUserInfoOther(@RequestHeader(HttpConstants.AUTHENTICATION) String token,@RequestParam("userId") String userId) {
        return userService.getUserInfoOther(token,userId);
    }

    @GetMapping("/getUserFavorites")
    public List<UserPostListVO> getUserFavorites(String userId) {
        return userService.getUserFavorites(userId);
    }
}
